package com.parenting.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.parenting.entities.EvaluationDO;
import com.parenting.entities.ReplyDO;
import com.parenting.mapper.ReplyMapper;
import com.parenting.model.UserDTO;
import com.parenting.request.ReplyRequest;
import com.parenting.response.ReplyListResponse;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.parenting.service.EvaluationService;
import com.parenting.service.ReplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 回复表 服务实现类
 * </p>
 *
 * @author 烟台业达-王世玺
 * @since 2021-09-27
 */
@Service
@Slf4j
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, ReplyDO> implements ReplyService {

    @Override
    public List<ReplyListResponse> getReplyListResponse(String evaluationId) {
        List<ReplyDO> replyDOS = baseMapper.selectList(new LambdaQueryWrapper<ReplyDO>().eq(ReplyDO::getEvaluationId, evaluationId));
        if (null!=replyDOS&&replyDOS.size()>0) {
            List<ReplyListResponse> list=new ArrayList<>();
            for (ReplyDO r : replyDOS) {
                list.add(BeanUtil.copyProperties(r,ReplyListResponse.class));
            }
            return list;
        }
        return null;
    }
    @Autowired
    private EvaluationService evaluationService;
    @Override
    public void addReply(ReplyRequest replyRequest, UserDTO user) {
        ReplyDO replyDO = BeanUtil.copyProperties(replyRequest, ReplyDO.class);
        replyDO.setReplyUserId(user.getId());
        replyDO.setShopId(user.getShopId());
        replyDO.setReplyUserName(user.getFullName());
        replyDO.setReplyUserHeadUrl(user.getImageUrl());
        replyDO.setState(1);
        replyDO.setClerk(1);
        //通过上一级ID查询 回复表是否有信息如果没有 那就是第一次回复
        ReplyDO reply = baseMapper.selectById(replyRequest.getEvaluationId());
        log.info("ReplyDO============= {}" ,reply);
        //第一次回复
        if (null == reply){
            //主题表信息
            EvaluationDO byId = evaluationService.getById(replyRequest.getEvaluationId());
            //封装第一次
            baseMapper.insert(replyDO);
            byId.setState(2);
            boolean b = evaluationService.updateById(byId);
            log.info("boolean=evaluationService============ {}" ,b);
        }else{
            reply.setState(2);
            int i = baseMapper.updateById(reply);
            log.info("boolean=baseMapper============ {}" ,i);
            String evaluationId = reply.getEvaluationId();
            replyDO.setEvaluationId(evaluationId);
            baseMapper.insert(replyDO);

        }
    }
}
